package cn.edu.baiyunu.myapplication.ui.edit

import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Lightbulb
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.ViewModelProvider
import cn.edu.baiyunu.myapplication.MainActivity
import cn.edu.baiyunu.myapplication.data.model.PhotoSpec
import cn.edu.baiyunu.myapplication.R
import android.graphics.Canvas
import android.graphics.Paint
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.BorderStroke
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.ui.graphics.vector.ImageVector
import kotlinx.coroutines.launch
import cn.edu.baiyunu.myapplication.ui.components.PatternDotsBackground
import cn.edu.baiyunu.myapplication.utils.MessageType
import cn.edu.baiyunu.myapplication.utils.showMessage

/**
 * 照片编辑屏幕 - 按照原型图实现
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditScreen(
    viewModel: EditViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToResult: () -> Unit
) {
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    val scrollState = rememberScrollState()
    
    var showExitDialog by remember { mutableStateOf(false) }
    var showSaveDialog by remember { mutableStateOf(false) }
    
    // 获取ViewModel中的状态
    val currentBitmap by viewModel.currentBitmap.observeAsState()
    val isProcessing by viewModel.isProcessing.collectAsState()
    val portraitExtracted by viewModel.portraitExtracted.collectAsState()
    val gestureScale by viewModel.gestureScale.collectAsState()
    val offsetX by viewModel.offsetX.collectAsState()
    val offsetY by viewModel.offsetY.collectAsState()
    val activeTab by viewModel.activeTab.collectAsState()
    val showPreview by viewModel.showPreview.collectAsState()
    val previewBitmap by viewModel.previewBitmap.observeAsState()
    
    // 参考画布相关
    val referenceCanvasSpec by viewModel.referenceCanvasSpec.collectAsState()
    val actualCanvasSpec by viewModel.actualCanvasSpec.collectAsState()
    val showReferenceBorder by viewModel.showReferenceCanvasBorder.collectAsState()
    
    // 全屏模式和画布边界检测
    val isFullScreenMode by viewModel.isFullScreenMode.collectAsState()
    val isImageExceedCanvas by viewModel.isImageExceedCanvas.collectAsState()
    
    // 保存确认对话框
    if (showSaveDialog) {
        AlertDialog(
            onDismissRequest = { showSaveDialog = false },
            title = { Text("保存照片") },
            text = { Text("保存当前编辑的照片？保存后可以在历史记录中查看。") },
            confirmButton = {
                TextButton(
                    onClick = { 
                        showSaveDialog = false
                        viewModel.saveSingleImageAndNavigate(onNavigateToResult)
                    }
                ) { Text("确认保存") }
            },
            dismissButton = {
                TextButton(onClick = { showSaveDialog = false }) { Text("取消") }
            }
        )
    }
    
    // 退出确认对话框
    if (showExitDialog) {
        AlertDialog(
            onDismissRequest = { showExitDialog = false },
            title = { Text("退出编辑") },
            text = { Text("确定要放弃当前的编辑吗？未保存的更改将会丢失。") },
            confirmButton = {
                TextButton(onClick = { 
                    showExitDialog = false
                    onNavigateBack() 
                }) { Text("确认退出") }
            },
            dismissButton = {
                TextButton(onClick = { showExitDialog = false }) { Text("取消") }
            }
        )
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("照片编辑") },
                    navigationIcon = {
                        IconButton(onClick = { showExitDialog = true }) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                        }
                    },
                    actions = {
                        // 全屏模式切换按钮
                        IconButton(onClick = { viewModel.toggleFullScreenMode() }) {
                            if (isFullScreenMode) {
                                Icon(Icons.Default.FullscreenExit, contentDescription = "退出全屏")
                            } else {
                                Icon(Icons.Default.Fullscreen, contentDescription = "全屏模式")
                            }
                        }
                        
                        IconButton(onClick = { viewModel.togglePreview() }) {
                            Icon(Icons.Default.Preview, contentDescription = "预览")
                        }
                        IconButton(onClick = { showSaveDialog = true }) {
                            Icon(Icons.Default.Save, contentDescription = "保存")
                        }
                        IconButton(onClick = { viewModel.resetEdits() }) {
                            Icon(Icons.Default.Refresh, contentDescription = "重置")
                        }
                    }
                )
            },
            snackbarHost = { SnackbarHost(snackbarHostState) },
            content = { paddingValues ->
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .padding(horizontal = 16.dp, vertical = 8.dp)
                        .verticalScroll(scrollState)
                ) {
                    // 图像编辑区域
                    EditCanvasArea(
                        bitmap = currentBitmap,
                        isProcessing = isProcessing,
                        gestureScale = gestureScale,
                        offsetX = offsetX,
                        offsetY = offsetY,
                        onScaleChange = { viewModel.updateGestureScale(it) },
                        onOffsetChange = { x, y -> viewModel.updateOffset(x, y) },
                        referenceSpec = referenceCanvasSpec,
                        actualSpec = actualCanvasSpec,
                        showReferenceBorder = showReferenceBorder,
                        isFullScreenMode = isFullScreenMode,
                        isImageExceedCanvas = isImageExceedCanvas
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 功能选项卡
                    ScrollableTabRow(
                        selectedTabIndex = activeTab.ordinal,
                        edgePadding = 8.dp,
                        containerColor = Color.White,
                        contentColor = Color(0xFF0F766E),
                        indicator = { tabPositions ->
                            androidx.compose.material3.TabRowDefaults.SecondaryIndicator(
                                Modifier.tabIndicatorOffset(tabPositions[activeTab.ordinal]),
                                color = Color(0xFF0F766E),
                                height = 2.dp
                            )
                        }
                    ) {
                        EditTab.values().forEach { tab ->
                            Tab(
                                selected = activeTab == tab,
                                onClick = { viewModel.setActiveTab(tab) },
                                text = { 
                                    Text(
                                        text = tab.title,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis
                                    )
                                }
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 选项卡内容
                        Box(
                            modifier = Modifier
                            .fillMaxWidth()
                            .background(Color.White)
                            .padding(8.dp)
                    ) {
                        when (activeTab) {
                            EditTab.PORTRAIT_MATTING -> {
                                // 人像抠图功能
                                PortraitMattingOptions(
                                    portraitExtracted = portraitExtracted,
                                    selectedBgColor = viewModel.selectedBgColor.collectAsState().value,
                                    selectedBgColors = viewModel.selectedBgColors.collectAsState().value,
                                    onExtractPortrait = { viewModel.extractPortrait() },
                                    onChangeBackground = { viewModel.changeBackgroundColor(it) },
                                    onToggleBackground = { viewModel.toggleBackgroundColor(it) },
                                    isColorSelected = { viewModel.isColorSelected(it) },
                                    onBatchExport = {
                                        viewModel.saveBatchImagesAndNavigate {
                                            onNavigateToResult()
                                        }
                                    }
                                )
                            }
                            EditTab.SPECS -> {
                                // 规格选择
                                SpecsTabContent(
                                    availablePhotoSpecs = viewModel.availablePhotoSpecs.collectAsState().value,
                                    selectedPhotoSpec = viewModel.selectedPhotoSpec.collectAsState().value,
                                    onPhotoSpecSelected = { viewModel.selectPhotoSpec(it) },
                                    onTogglePreview = { viewModel.togglePreview() },
                                    onApplySpec = { viewModel.applySelectedSpec() }
                                )
                            }
                            EditTab.TRANSFORM -> {
                                // 变换选项卡
                                TransformTabContent(
                                    scale = gestureScale,
                                    onScaleChange = { viewModel.updateGestureScale(it) },
                                    onReset = { viewModel.resetGestureTransformation() }
                                )
                            }
                            EditTab.CANVAS_SETTINGS -> {
                                // 画布设置
                                CanvasSettingsContent(
                                    viewModel = viewModel,
                                    canvasRatio = viewModel.canvasRatio.collectAsState().value,
                                    showReferenceBorder = viewModel.showReferenceCanvasBorder.collectAsState().value,
                                    isPortraitExtracted = portraitExtracted
                                )
                            }
                        }
                    }
                }
            }
        )
        
        // 显示预览窗口
        if (showPreview && previewBitmap != null) {
            PreviewWindow(
                bitmap = previewBitmap,
                spec = viewModel.selectedPhotoSpec.collectAsState().value,
                dpi = viewModel.selectedDpi.collectAsState().value,
                onDismiss = { viewModel.togglePreview() }
            )
        }
    }
}

/**
 * 玻璃卡片 - 模仿原型图中的glass-card效果
 */
@Composable
fun GlassCard(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.7f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
        shape = RoundedCornerShape(16.dp)
    ) {
                                Box(
                                    modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            content()
        }
    }
}

/**
 * 编辑选项卡 - 只保留人像抠图和裁剪选项
 */
@Composable
private fun EditTabs(
    activeTab: EditTab,
    onTabSelected: (EditTab) -> Unit
) {
    val tabs = EditTab.values()
    
    ScrollableTabRow(
        selectedTabIndex = activeTab.ordinal,
        edgePadding = 0.dp,
        containerColor = Color.White,
        contentColor = Color(0xFF14B8A6),
        indicator = { tabPositions ->
            Box(
                Modifier
                    .tabIndicatorOffset(tabPositions[activeTab.ordinal])
                    .height(3.dp)
                    .background(
                        color = Color(0xFF0F766E),
                        shape = RoundedCornerShape(topStart = 3.dp, topEnd = 3.dp)
                    )
            )
        },
        divider = { Divider(color = Color(0xFFE2E8F0)) }
    ) {
        tabs.forEachIndexed { index, tab ->
            Tab(
                selected = index == activeTab.ordinal,
                onClick = { onTabSelected(tab) },
                text = {
                                        Text(
                        text = tab.title,
                        fontSize = 15.sp,
                        fontWeight = if (index == activeTab.ordinal) FontWeight.Bold else FontWeight.Normal
                    )
                }
            )
        }
    }
}

/**
 * 人像抠图选项 - 提供抠图功能和背景色选择
 */
@Composable
fun PortraitMattingOptions(
    portraitExtracted: Boolean,
    selectedBgColor: Int,
    selectedBgColors: Set<Int>,
    onExtractPortrait: () -> Unit,
    onChangeBackground: (Int) -> Unit,
    onToggleBackground: (Int) -> Unit,
    isColorSelected: (Int) -> Boolean,
    onBatchExport: (() -> Unit)? = null
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 抠图操作按钮
        Button(
            onClick = onExtractPortrait,
                        modifier = Modifier
                            .fillMaxWidth()
                .height(48.dp),
            shape = RoundedCornerShape(12.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFF14B8A6),
                contentColor = Color.White
            )
        ) {
            Icon(
                imageVector = Icons.Default.AutoFixHigh,
                contentDescription = "抠图"
            )
            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                text = if (portraitExtracted) "重新抠图" else "一键抠图",
                                fontSize = 16.sp
                            )
        }
        
        // 仅在已抠图后显示背景颜色选择
        if (portraitExtracted) {
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                    Text(
                    text = "选择背景颜色",
                    fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                    color = Color(0xFF334155)
                )
                
                Text(
                    text = "已选择 ${selectedBgColors.size} 种颜色",
                    fontSize = 14.sp,
                    color = Color(0xFF64748B)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 背景颜色选择器 - 新增多选功能
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 蓝色背景
                MultiSelectColorCircle(
                    color = Color(0xFF0078D7),
                    isCurrentColor = selectedBgColor == 0xFF0078D7.toInt(),
                    isSelected = isColorSelected(0xFF0078D7.toInt()),
                    onColorClick = { onChangeBackground(0xFF0078D7.toInt()) },
                    onLongClick = { onToggleBackground(0xFF0078D7.toInt()) }
                )
                
                // 红色背景
                MultiSelectColorCircle(
                    color = Color(0xFFE81123),
                    isCurrentColor = selectedBgColor == 0xFFE81123.toInt(),
                    isSelected = isColorSelected(0xFFE81123.toInt()),
                    onColorClick = { onChangeBackground(0xFFE81123.toInt()) },
                    onLongClick = { onToggleBackground(0xFFE81123.toInt()) }
                )
                
                // 绿色背景
                MultiSelectColorCircle(
                    color = Color(0xFF107C10),
                    isCurrentColor = selectedBgColor == 0xFF107C10.toInt(),
                    isSelected = isColorSelected(0xFF107C10.toInt()),
                    onColorClick = { onChangeBackground(0xFF107C10.toInt()) },
                    onLongClick = { onToggleBackground(0xFF107C10.toInt()) }
                )
                
                // 白色背景
                MultiSelectColorCircle(
                    color = Color.White,
                    isCurrentColor = selectedBgColor == android.graphics.Color.WHITE,
                    isSelected = isColorSelected(android.graphics.Color.WHITE),
                    onColorClick = { onChangeBackground(android.graphics.Color.WHITE) },
                    onLongClick = { onToggleBackground(android.graphics.Color.WHITE) }
                )
                
                // 黑色背景
                MultiSelectColorCircle(
                    color = Color.Black,
                    isCurrentColor = selectedBgColor == android.graphics.Color.BLACK,
                    isSelected = isColorSelected(android.graphics.Color.BLACK),
                    onColorClick = { onChangeBackground(android.graphics.Color.BLACK) },
                    onLongClick = { onToggleBackground(android.graphics.Color.BLACK) }
                )
            }
            
            // 多选提示
            Surface(
                color = Color(0x1114B8A6),
                shape = RoundedCornerShape(8.dp),
                modifier = Modifier.fillMaxWidth()
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                        imageVector = Icons.Outlined.Lightbulb,
                        contentDescription = "提示",
                        tint = Color(0xFF14B8A6)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
            Text(
                        text = "点击切换预览颜色，长按选择/取消选择多个背景颜色批量导出",
                        fontSize = 14.sp,
                        color = Color(0xFF14B8A6)
                    )
                }
            }
            
            // 批量导出解释
            Surface(
                color = Color(0x11F59E0B),
                shape = RoundedCornerShape(8.dp),
                            modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp)
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                        imageVector = Icons.Outlined.Info,
                        contentDescription = "说明",
                        tint = Color(0xFFF59E0B)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "批量导出将根据当前选择的规格和裁剪区域，生成标准尺寸的图片，不会有空白区域",
                        fontSize = 14.sp,
                        color = Color(0xFFB45309)
                    )
                }
            }
            
            // 批量导出按钮 - 当选择了多个背景颜色时显示
            if (selectedBgColors.size > 1 && onBatchExport != null) {
                Spacer(modifier = Modifier.height(16.dp))
                
                Button(
                    onClick = onBatchExport,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    shape = RoundedCornerShape(12.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFFEA580C), // 橙色
                        contentColor = Color.White
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.SaveAlt,
                        contentDescription = "批量导出"
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "批量导出 ${selectedBgColors.size} 种背景",
                        fontSize = 16.sp
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 技术说明
            Surface(
                color = Color(0x1114B8A6),
                shape = RoundedCornerShape(8.dp),
                modifier = Modifier.fillMaxWidth()
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                        imageVector = Icons.Outlined.Lightbulb,
                        contentDescription = "提示",
                        tint = Color(0xFF14B8A6)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                        Text(
                        text = "人像抠图使用MODNet模型，提取前景人物并自动生成透明背景。",
                        fontSize = 14.sp,
                        color = Color(0xFF14B8A6)
                    )
                }
            }
        }
    }
}

/**
 * 裁剪选项 - 提供裁剪缩放功能
 */
@Composable
fun CropOptions(
    scale: Float,
    onScaleChange: (Float) -> Unit,
    onReset: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 缩放选项
        Text(
            text = "缩放比例: ${(scale * 100).toInt()}%",
            fontSize = 16.sp,
            fontWeight = FontWeight.Medium,
            color = Color(0xFF334155)
        )
        
        // 缩放滑块
        Slider(
            value = scale,
            onValueChange = onScaleChange,
            valueRange = 0.5f..2.0f,
            steps = 30,
            colors = SliderDefaults.colors(
                thumbColor = Color(0xFF14B8A6),
                activeTrackColor = Color(0xFF14B8A6),
                inactiveTrackColor = Color(0xFFCBD5E1)
            )
        )
        
        // 复位按钮
                    Button(
            onClick = onReset,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFFF1F5F9),
                contentColor = Color(0xFF334155)
            ),
            shape = RoundedCornerShape(8.dp),
                        modifier = Modifier
                            .fillMaxWidth()
                .height(40.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Refresh,
                contentDescription = "复位"
            )
            Spacer(modifier = Modifier.width(8.dp))
                        Text(
                text = "复位缩放和位置",
                fontSize = 14.sp
                        )
                    }
    }
}

/**
 * 多选颜色圆圈
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MultiSelectColorCircle(
    color: Color,
    isCurrentColor: Boolean,
    isSelected: Boolean,
    onColorClick: () -> Unit,
    onLongClick: () -> Unit
    ) {
        Box(
            modifier = Modifier
            .size(48.dp)
            .border(
                width = if (isCurrentColor) 3.dp else if (isSelected) 2.dp else 1.dp,
                color = if (isCurrentColor) Color(0xFF14B8A6) 
                       else if (isSelected) Color(0xFF14B8A6).copy(alpha = 0.7f) 
                       else Color.Transparent,
                shape = CircleShape
            )
            .padding(4.dp)
            .clip(CircleShape)
            .background(color)
            .combinedClickable(
                onClick = onColorClick,
                onLongClick = onLongClick
            )
    ) {
        if (isSelected) {
            Icon(
                imageVector = Icons.Default.Check,
                contentDescription = "已选择",
                tint = if (color == Color.White) Color.Black else Color.White,
                modifier = Modifier
                    .size(20.dp)
                    .align(Alignment.Center)
            )
        }
    }
}

/**
 * 颜色选择圆圈
 */
@Composable
fun ColorCircle(
    color: Color,
    selected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .size(48.dp)
            .border(
                width = 2.dp,
                color = if (selected) Color(0xFF0F766E) else Color.Transparent,
                shape = CircleShape
            )
            .padding(4.dp)
            .clip(CircleShape)
            .background(color)
            .clickable { onClick() }
    ) {
        if (selected) {
            Icon(
                imageVector = Icons.Default.Check,
                contentDescription = "已选择",
                tint = if (color == Color.White) Color.Black else Color.White,
                modifier = Modifier.align(Alignment.Center)
            )
        }
    }
}

/**
 * 带标签的滑块组件
 */
@Composable
fun SliderWithLabel(
    label: String,
    value: Float,
    onValueChange: (Float) -> Unit
) {
    Column {
        // 标签和百分比显示
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = label,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF334155)
            )
            
            Text(
                text = "${(value * 100).toInt()}%",
                fontSize = 14.sp,
                color = Color(0xFF64748B)
            )
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 滑块
        Slider(
            value = value,
            onValueChange = onValueChange,
            valueRange = 0f..1f,
            colors = SliderDefaults.colors(
                thumbColor = Color(0xFF0F766E),
                activeTrackColor = Color(0xFF0F766E),
                inactiveTrackColor = Color(0xFFCBD5E1)
            )
        )
    }
}

/**
 * 编辑选项卡内容
 */
@Composable
fun EditTabContent(
    tab: EditTab,
    viewModel: EditViewModel,
    onSelectSpec: (cn.edu.baiyunu.myapplication.data.model.PhotoSpec) -> Unit,
    isPortraitExtracted: Boolean,
    onNavigateToResult: () -> Unit
) {
    when (tab) {
        EditTab.PORTRAIT_MATTING -> {
            // 使用PortraitMattingOptions组件提供抠图功能
            PortraitMattingOptions(
                portraitExtracted = isPortraitExtracted,
                selectedBgColor = viewModel.selectedBgColor.collectAsState().value,
                selectedBgColors = viewModel.selectedBgColors.collectAsState().value,
                onExtractPortrait = { viewModel.extractPortrait() },
                onChangeBackground = { viewModel.changeBackgroundColor(it) },
                onToggleBackground = { viewModel.toggleBackgroundColor(it) },
                isColorSelected = { viewModel.isColorSelected(it) },
                onBatchExport = {
                    viewModel.saveBatchImagesAndNavigate {
                        onNavigateToResult()
                    }
                }
            )
        }
        
        EditTab.SPECS -> {
            // 规格选择内容
            SpecsTabContent(
                availablePhotoSpecs = viewModel.availablePhotoSpecs.collectAsState().value,
                selectedPhotoSpec = viewModel.selectedPhotoSpec.collectAsState().value,
                onPhotoSpecSelected = onSelectSpec,
                onTogglePreview = { viewModel.togglePreview() },
                onApplySpec = { viewModel.applySelectedSpec() }
            )
        }
        
        EditTab.TRANSFORM -> {
            // 变换选项卡内容
            TransformTabContent(
                scale = viewModel.gestureScale.collectAsState().value,
                onScaleChange = { viewModel.updateGestureScale(it) },
                onReset = { viewModel.resetGestureTransformation() }
            )
        }
        
        EditTab.CANVAS_SETTINGS -> {
            // 画布设置选项卡内容
            CanvasSettingsContent(
                viewModel = viewModel,
                canvasRatio = viewModel.canvasRatio.collectAsState().value,
                showReferenceBorder = viewModel.showReferenceCanvasBorder.collectAsState().value,
                isPortraitExtracted = isPortraitExtracted
            )
        }
    }
}

/**
 * 证件照规格选择内容
 */
@Composable
fun SpecsTabContent(
    availablePhotoSpecs: List<PhotoSpec>,
    selectedPhotoSpec: PhotoSpec?,
    onPhotoSpecSelected: (PhotoSpec) -> Unit,
    onTogglePreview: () -> Unit,
    onApplySpec: () -> Unit
) {
    Column(
            modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        // 标题
            Text(
            text = "选择证件照规格",
            fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
            color = Color(0xFF334155),
            modifier = Modifier.padding(bottom = 12.dp)
        )
        
        // 分类证件照规格
        val domesticSpecs = availablePhotoSpecs.filter { 
            it.name.contains("寸") || it.name.contains("身份证") || it.name.contains("驾驶证")
        }
        
        val internationalSpecs = availablePhotoSpecs.filter { 
            it.name.contains("护照") || it.name.contains("签证") 
        }
        
        val otherSpecs = availablePhotoSpecs.filter { spec ->
            !domesticSpecs.contains(spec) && !internationalSpecs.contains(spec)
        }
        
        // 国内证件照规格
        if (domesticSpecs.isNotEmpty()) {
        Text(
                text = "国内证件照",
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF64748B),
                modifier = Modifier.padding(vertical = 8.dp)
            )
            
            LazyRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(horizontal = 4.dp)
            ) {
                items(domesticSpecs) { spec ->
                    HorizontalSpecCard(
                        spec = spec,
                        isSelected = selectedPhotoSpec?.id == spec.id,
                        isReferenceOnly = false,
                        isConfirmed = false,
                        onClick = { onPhotoSpecSelected(spec) }
                    )
                }
            }
        }
        
        // 国际证件照规格
        if (internationalSpecs.isNotEmpty()) {
            Text(
                text = "国际证件照",
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF64748B),
                modifier = Modifier.padding(vertical = 8.dp)
            )
            
            LazyRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(horizontal = 4.dp)
            ) {
                items(internationalSpecs) { spec ->
                    HorizontalSpecCard(
                        spec = spec,
                        isSelected = selectedPhotoSpec?.id == spec.id,
                        isReferenceOnly = false,
                        isConfirmed = false,
                        onClick = { onPhotoSpecSelected(spec) }
                    )
                }
            }
        }
        
        // 其他规格
        if (otherSpecs.isNotEmpty()) {
            Text(
                text = "其他规格",
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF64748B),
                modifier = Modifier.padding(vertical = 8.dp)
            )
            
            LazyRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(horizontal = 4.dp)
            ) {
                items(otherSpecs) { spec ->
                    HorizontalSpecCard(
                        spec = spec,
                        isSelected = selectedPhotoSpec?.id == spec.id,
                        isReferenceOnly = false,
                        isConfirmed = false,
                        onClick = { onPhotoSpecSelected(spec) }
                    )
                }
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // AI智能填充提示
        Surface(
            color = Color(0x1114B8A6),
            shape = RoundedCornerShape(8.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier.padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Default.AutoFixHigh,
                    contentDescription = "等比例调整",
                    tint = Color(0xFF14B8A6)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "小图片应用大规格时，系统将自动填充边缘",
                    fontSize = 14.sp,
                    color = Color(0xFF14B8A6)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 操作按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // 预览按钮
            Button(
                onClick = onTogglePreview,
                modifier = Modifier
                    .weight(1f)
                    .height(48.dp),
                shape = RoundedCornerShape(8.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFE2E8F0),
                    contentColor = Color(0xFF334155)
                ),
                enabled = selectedPhotoSpec != null
            ) {
                Text("预览效果")
            }
            
            // 应用按钮
            Button(
                onClick = onApplySpec,
                modifier = Modifier
                    .weight(1f)
                    .height(48.dp),
                shape = RoundedCornerShape(8.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF14B8A6),
                    contentColor = Color.White
                ),
                enabled = selectedPhotoSpec != null
            ) {
                Text("应用规格")
            }
        }
    }
}

/**
 * 水平规格卡片 - 简洁轻量标签式样式
 */
@Composable
fun HorizontalSpecCard(
    spec: PhotoSpec,
    isSelected: Boolean,
    isReferenceOnly: Boolean,
    isConfirmed: Boolean,
    onClick: () -> Unit
) {
    val backgroundColor = when {
        isConfirmed -> Color(0xFF34D399) // 已确认的规格用绿色
        isSelected -> Color(0xFF3B82F6) // 选中的参考规格用蓝色
        else -> Color(0xFFF1F5F9) // 未选中的规格用浅灰色
    }
    
    val textColor = if (isSelected || isConfirmed) Color.White else Color(0xFF475569)
    
    Surface(
        modifier = Modifier
            .padding(end = 8.dp, bottom = 8.dp)
            .clickable { onClick() },
        shape = RoundedCornerShape(100.dp), // 圆形边角
        color = backgroundColor,
        border = if (isReferenceOnly) BorderStroke(1.dp, Color(0xFF3B82F6)) else null
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            if (isConfirmed) {
            Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "已确认",
                    modifier = Modifier.size(16.dp),
                    tint = Color.White
                )
                Spacer(modifier = Modifier.width(4.dp))
            } else if (isReferenceOnly) {
                Icon(
                    imageVector = Icons.Default.CropFree,
                    contentDescription = "参考",
                    modifier = Modifier.size(16.dp),
                    tint = Color(0xFF3B82F6)
                )
                Spacer(modifier = Modifier.width(4.dp))
            }
            
                Text(
                text = spec.name,
                style = MaterialTheme.typography.bodyMedium,
                color = textColor
            )
        }
    }
}

/**
 * 简化版规格选项（用于简单展示，不带图片）
 */
@Composable
fun SimpleSpecItem(
    spec: PhotoSpec,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .width(120.dp)
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) Color(0xFFCCFBF1) else Color.White,
            contentColor = if (isSelected) Color(0xFF0F766E) else Color(0xFF334155)
        ),
        shape = RoundedCornerShape(12.dp),
        border = if (isSelected) BorderStroke(1.dp, Color(0xFF14B8A6)) else null
) {
    Column(
            modifier = Modifier
                .padding(12.dp)
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = spec.name,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            Text(
                text = "${spec.width}×${spec.height}mm",
                fontSize = 12.sp,
                color = if (isSelected) Color(0xFF0F766E) else Color(0xFF64748B)
            )
        }
    }
}

/**
 * 预览对话框
 */
@Composable
fun PreviewDialog(
    previewBitmap: Bitmap?,
    selectedSpec: PhotoSpec?,
    onDismiss: () -> Unit,
    onApply: () -> Unit
) {
    if (previewBitmap == null) return

    Dialog(
        onDismissRequest = onDismiss
    ) {
        Column(
        modifier = Modifier
            .fillMaxWidth()
                .background(Color.White, RoundedCornerShape(16.dp))
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 标题
            Text(
                text = "证件照预览",
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp,
                color = Color(0xFF334155),
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            // 规格信息
            selectedSpec?.let { spec ->
            Text(
                    text = "${spec.name} (${spec.description})",
                    fontSize = 14.sp,
                    color = Color(0xFF64748B),
                    modifier = Modifier.padding(bottom = 16.dp)
                )
            }
            
            // 预览图
            Image(
                bitmap = previewBitmap.asImageBitmap(),
                contentDescription = "预览图",
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(previewBitmap.width.toFloat() / previewBitmap.height.toFloat())
                    .border(1.dp, Color(0xFFCBD5E1), RoundedCornerShape(8.dp))
                    .clip(RoundedCornerShape(8.dp)),
                contentScale = ContentScale.Fit
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                TextButton(
                    onClick = onDismiss,
                    modifier = Modifier.weight(1f)
                ) {
                    Text("取消", color = Color(0xFF64748B))
                }
                
                Button(
                    onClick = onApply,
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF14B8A6)
                    )
                ) {
                    Text("应用")
                }
            }
        }
    }
}

/**
 * 自适应模式选项卡片
 */
@Composable
private fun AdaptModeOption(
    title: String,
    description: String,
    icon: ImageVector,
    onClick: () -> Unit
) {
    Surface(
            modifier = Modifier
            .width(140.dp)
            .clickable { onClick() },
            shape = RoundedCornerShape(12.dp),
        color = Color(0xFFF8FAFC),
        border = BorderStroke(1.dp, Color(0xFFE2E8F0))
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = icon,
                contentDescription = title,
                tint = Color(0xFF14B8A6),
                modifier = Modifier
                    .size(32.dp)
                    .padding(bottom = 8.dp)
            )
            
            Text(
                text = title,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF334155)
            )
            
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall,
                color = Color(0xFF64748B),
                textAlign = TextAlign.Center,
                fontSize = 12.sp
            )
        }
    }
}

/**
 * 规格选择部分
 */
@Composable
fun SpecSection(
    specs: List<PhotoSpec>,
    selectedSpec: PhotoSpec?,
    referenceSpec: PhotoSpec?,
    confirmedSpec: PhotoSpec?,
    onSpecClick: (PhotoSpec) -> Unit
            ) {
                Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
                ) {
            Text(
            text = "证件规格",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold,
                color = Color(0xFF334155)
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
        LazyRow(
            contentPadding = PaddingValues(vertical = 4.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            items(specs) { spec ->
                // 判断规格状态
                val isSelected = selectedSpec?.id == spec.id
                val isConfirmed = confirmedSpec?.id == spec.id
                val isReferenceOnly = referenceSpec?.id == spec.id && !isConfirmed
                
                HorizontalSpecCard(
                    spec = spec,
                    isSelected = isSelected,
                    isReferenceOnly = isReferenceOnly,
                    isConfirmed = isConfirmed,
                    onClick = { onSpecClick(spec) }
                )
            }
        }
    }
}

/**
 * 编辑区域画布 - 包含图像和参考框
 */
@Composable
fun EditCanvasArea(
    bitmap: Bitmap?,
    isProcessing: Boolean,
    gestureScale: Float,
    offsetX: Float,
    offsetY: Float,
    onScaleChange: (Float) -> Unit,
    onOffsetChange: (Float, Float) -> Unit,
    referenceSpec: PhotoSpec?,
    actualSpec: PhotoSpec?,
    showReferenceBorder: Boolean,
    isFullScreenMode: Boolean,
    isImageExceedCanvas: Boolean
) {
    val density = LocalDensity.current
    val context = LocalContext.current
    
    // 计算参考画布和实际画布尺寸比例
    val canvasRatio = if (referenceSpec != null && actualSpec != null) {
        referenceSpec.width / actualSpec.width
    } else {
        1.5f // 默认参考画布是实际画布的1.5倍
    }
    
    // 更精确地计算像素密度和屏幕尺寸
    val displayMetrics = context.resources.displayMetrics
    val screenWidthDp = with(density) { displayMetrics.widthPixels.toDp() }
    val screenHeightDp = with(density) { displayMetrics.heightPixels.toDp() }
    val screenDensity = displayMetrics.density
    
    // 计算DPI和毫米到dp的转换系数
    val dpi = 160f * screenDensity
    val mmToDp = dpi / 25.4f // 1英寸 = 25.4毫米
    
    // 实际画布宽高（用于渲染边框）
    val actualCanvasWidth = if (actualSpec != null && referenceSpec != null) {
        // 使用与参考画布相同的比例因子，但根据实际画布的尺寸计算
        referenceSpec.width * 5 / canvasRatio // 使用相同的比例因子5，但根据比例适配
    } else if (actualSpec != null) {
        actualSpec.width * 5 // 保留原来的缩放因子5
    } else {
        100f // 默认值
    }
    
    val actualCanvasHeight = if (actualSpec != null && referenceSpec != null) {
        // 使用与参考画布相同的比例因子，但根据实际画布的尺寸计算
        referenceSpec.height * 5 / canvasRatio // 使用相同的比例因子5，但根据比例适配
    } else if (actualSpec != null) {
        actualSpec.height * 5 // 保留原来的缩放因子5
    } else {
        140f // 默认值
    }
    
    // 编辑区容器，根据全屏模式调整高度
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .then(
                if (isFullScreenMode) {
                    // 全屏模式下使用更大的固定高度，或者使用屏幕高度
                    Modifier.height(screenHeightDp - 150.dp) // 减去顶部栏和底部一些空间
                } else {
                    // 常规模式下使用正方形
                    Modifier.aspectRatio(1f)
                }
            )
            .clip(RoundedCornerShape(8.dp))
            .background(Color(0xFFF1F5F9))
            .padding(8.dp),
        contentAlignment = Alignment.Center
    ) {
        if (bitmap != null) {
            var scale by remember { mutableStateOf(gestureScale) }
            var offsetXState by remember { mutableStateOf(offsetX) }
            var offsetYState by remember { mutableStateOf(offsetY) }
            
            // 使用LaunchedEffect监听ViewModel中的值变化
            LaunchedEffect(gestureScale, offsetX, offsetY) {
                scale = gestureScale
                offsetXState = offsetX
                offsetYState = offsetY
            }
            
            val transformableState = rememberTransformableState { zoomChange, panChange, _ ->
                scale = (scale * zoomChange).coerceIn(0.1f, 3f) // 允许最小缩放到0.1倍
                
                offsetXState += panChange.x
                offsetYState += panChange.y
                
                // 通知ViewModel
                onScaleChange(scale)
                onOffsetChange(offsetXState, offsetYState)
            }
            
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .clip(RoundedCornerShape(8.dp))
                    .background(Color.White)
            ) {
                // 图像显示区域
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .transformable(state = transformableState)
                ) {
                    // 创建裁剪区域，只显示实际画布（绿色框）内的内容
                    Box(
                        modifier = Modifier
                            .size(
                                width = actualCanvasWidth.dp,
                                height = actualCanvasHeight.dp
                            )
                            .align(Alignment.Center)
                            .clip(RoundedCornerShape(4.dp)) // 与边框的圆角保持一致
                    ) {
                        // 在裁剪区域内显示图像
                        Image(
                            bitmap = bitmap.asImageBitmap(),
                            contentDescription = "编辑中的证件照",
                            modifier = Modifier
                                .fillMaxSize()
                                .graphicsLayer(
                                    scaleX = scale,
                                    scaleY = scale,
                                    translationX = offsetXState,
                                    translationY = offsetYState
                                ),
                            contentScale = ContentScale.Fit
                        )
                    }

                    // 显示参考画布边框
                    if (showReferenceBorder && referenceSpec != null && actualSpec != null) {
                        // 强制刷新UI的key
                        val refreshKey = remember { System.currentTimeMillis() }
                        
                        // 参考画布边框 - 外框（根据是否全屏模式调整大小）
                        val referenceModifier = if (isFullScreenMode) {
                            // 全屏模式下，参考画布根据实际画布等比例放大
                            val ratio = (screenHeightDp - 150.dp) / screenHeightDp
                            Modifier
                                .size(
                                    width = (referenceSpec.width * mmToDp).dp * ratio,
                                    height = (referenceSpec.height * mmToDp).dp * ratio
                                )
                                .align(Alignment.Center)
                        } else {
                            // 常规模式下
                            Modifier.fillMaxSize()
                        }
                        
                        Box(
                            modifier = referenceModifier
                                .border(
                                    width = 1.dp,
                                    color = Color(0xFF64748B).copy(alpha = 0.3f),
                                    shape = RoundedCornerShape(4.dp)
                                )
                        ) {
                            // 添加参考画布标签
                            Box(
                                modifier = Modifier
                                    .align(Alignment.TopEnd)
                                    .padding(4.dp)
                                    .background(
                                        color = Color(0xFF64748B).copy(alpha = 0.7f),
                                        shape = RoundedCornerShape(4.dp)
                                    )
                                    .padding(horizontal = 6.dp, vertical = 2.dp)
                ) {
                    Text(
                                    text = "参考画布 ${String.format("%.1f", canvasRatio)}×",
                                    color = Color.White,
                                    fontSize = 10.sp
                                )
                            }
                        }
                        
                        // 实际画布边框 - 内框（证件照实际输出区域）
                        // 根据是否超出边界改变颜色
                        val borderColor = if (isImageExceedCanvas) {
                            Color(0xFFFF9800) // 橙色警告
                        } else {
                            Color(0xFF0F766E) // 默认绿色
                        }
                        
                        // 根据全屏模式调整大小
                        val actualCanvasModifier = if (isFullScreenMode) {
                            // 全屏模式下，保持画布比例但放大
                            val ratio = (screenHeightDp - 150.dp) / screenHeightDp
                            Modifier
                                .size(
                                    width = actualCanvasWidth.dp * ratio,
                                    height = actualCanvasHeight.dp * ratio
                                )
                                .align(Alignment.Center)
                        } else {
                            // 常规模式下
                            Modifier
                                .size(
                                    width = with(density) { actualCanvasWidth.dp },
                                    height = with(density) { actualCanvasHeight.dp }
                                )
                                .align(Alignment.Center)
                        }
                        
                        Box(
                            modifier = actualCanvasModifier
                                .border(
                                    width = 1.5.dp,
                                    color = borderColor,
                                    shape = RoundedCornerShape(4.dp)
                                )
                        )
                        
                        // 添加实际画布标签
                        Box(
                            modifier = Modifier
                                .align(Alignment.BottomCenter)
                                .offset(y = (-8).dp)
                                .background(
                                    color = borderColor,
                                    shape = RoundedCornerShape(4.dp)
                                )
                                .padding(horizontal = 8.dp, vertical = 4.dp)
                        ) {
                            // 计算像素尺寸
                            val mmToInch = 0.0393701f
                            val dpiValue = 300f // 标准DPI
                            val widthPixels = (actualSpec.width * mmToInch * dpiValue).toInt()
                            val heightPixels = (actualSpec.height * mmToInch * dpiValue).toInt()
                    
                    Text(
                                text = "${actualSpec.width}×${actualSpec.height}mm (${widthPixels}×${heightPixels}px)",
                                color = Color.White,
                        fontSize = 12.sp,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
                
                // 加载指示器
                if (isProcessing) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black.copy(alpha = 0.5f)),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = Color.White
                        )
                    }
                }
            }
        } else {
            // 显示空状态
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .clip(RoundedCornerShape(8.dp))
                    .background(Color.White),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "请先选择照片",
                    color = Color(0xFF64748B),
                    fontSize = 16.sp
                )
            }
        }
    }
}

/**
 * 参考画布设置内容
 */
@Composable
fun CanvasSettingsContent(
    viewModel: EditViewModel,
    canvasRatio: Float,
    showReferenceBorder: Boolean,
    isPortraitExtracted: Boolean
            ) {
                Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 参考画布开关
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                text = "显示参考画布边框",
                fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                color = Color(0xFF334155)
            )
            
            Switch(
                checked = showReferenceBorder,
                onCheckedChange = { viewModel.toggleReferenceCanvasBorder() },
                colors = SwitchDefaults.colors(
                    checkedThumbColor = Color(0xFF0F766E),
                    checkedTrackColor = Color(0xFF0F766E).copy(alpha = 0.5f),
                    uncheckedThumbColor = Color(0xFF64748B),
                    uncheckedTrackColor = Color(0xFF64748B).copy(alpha = 0.3f)
                )
            )
        }
        
        // 参考画布比例设置
        Column {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                    Text(
                    text = "参考画布比例",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF334155)
                )
                
                Text(
                    text = "${String.format("%.1f", canvasRatio)}×",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF0F766E)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 改进的滑块，显示更明确的值域
            Slider(
                value = (canvasRatio - 1.1f) / 1.9f, // 将1.1f-3.0f映射到0f-1f
                onValueChange = { 
                    val newRatio = 1.1f + it * 1.9f // 从0f-1f映射回1.1f-3.0f
                    viewModel.setCanvasRatio(newRatio) 
                },
                valueRange = 0f..1f,
                steps = 19,
                colors = SliderDefaults.colors(
                    thumbColor = Color(0xFF0F766E),
                    activeTrackColor = Color(0xFF0F766E),
                    inactiveTrackColor = Color(0xFFCBD5E1)
                )
            )
            
            // 显示主要比例标记
            Row(
        modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 4.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text("1.0×", fontSize = 12.sp, color = Color(0xFF64748B))
                Text("1.5×", fontSize = 12.sp, color = Color(0xFF64748B))
                Text("2.0×", fontSize = 12.sp, color = Color(0xFF64748B))
                Text("2.5×", fontSize = 12.sp, color = Color(0xFF64748B))
                Text("3.0×", fontSize = 12.sp, color = Color(0xFF64748B))
            }
        }
        
        // 说明文本
        Text(
            text = "参考画布功能可以让您在更大区域内调整照片布局，最终保存时将只使用实际画布区域。比例越大，可调整空间越大。",
            fontSize = 14.sp,
            color = Color(0xFF64748B),
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    color = Color(0xFFE2F8F8),
                    shape = RoundedCornerShape(8.dp)
                )
                .padding(12.dp)
        )
        
        // 自动适应按钮
        Button(
            onClick = { viewModel.applyAutoAdaptToCanvas(EditViewModel.CanvasAdaptMode.FIT) },
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFF0F766E)
            ),
            shape = RoundedCornerShape(8.dp),
            modifier = Modifier
                .fillMaxWidth()
                .height(48.dp)
        ) {
            Icon(
                imageVector = Icons.Default.CenterFocusStrong,
                contentDescription = "自适应画布"
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "自动适应实际画布",
                fontSize = 14.sp
            )
        }
        
        // 填充模式按钮
        Button(
            onClick = { viewModel.applyAutoAdaptToCanvas(EditViewModel.CanvasAdaptMode.FILL) },
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFF0891B2)
            ),
            shape = RoundedCornerShape(8.dp),
        modifier = Modifier
                .fillMaxWidth()
                .height(48.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Crop,
                contentDescription = "填充画布"
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "填充模式（可能裁剪）",
                fontSize = 14.sp
            )
        }
    }
}

/**
 * 添加 TransformTabContent 函数 - 变换选项卡内容
 */
@Composable
fun TransformTabContent(
    scale: Float,
    onScaleChange: (Float) -> Unit,
    onReset: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 缩放选项，显示为百分比格式
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                text = "缩放比例",
                fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                color = Color(0xFF334155)
                )
                
                Text(
                text = "${(scale * 100).toInt()}%",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF0F766E)
            )
        }
        
        // 缩放滑块，显示为百分比 (10%-300%)
        Slider(
            value = (scale - 0.1f) / 2.9f, // 将0.1f-3.0f映射到0f-1f范围
            onValueChange = { 
                val newScale = 0.1f + it * 2.9f // 从0f-1f映射回0.1f-3.0f范围
                onScaleChange(newScale)
            },
            valueRange = 0f..1f,
            steps = 20,
            colors = SliderDefaults.colors(
                thumbColor = Color(0xFF14B8A6),
                activeTrackColor = Color(0xFF14B8A6),
                inactiveTrackColor = Color(0xFFCBD5E1)
            )
        )
        
        // 显示百分比标记
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 4.dp),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text("0%", fontSize = 12.sp, color = Color(0xFF64748B))
            Text("100%", fontSize = 12.sp, color = Color(0xFF64748B))
            Text("200%", fontSize = 12.sp, color = Color(0xFF64748B))
            Text("300%", fontSize = 12.sp, color = Color(0xFF64748B))
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 复位按钮
        Button(
            onClick = onReset,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFFF1F5F9),
                contentColor = Color(0xFF334155)
            ),
            shape = RoundedCornerShape(8.dp),
            modifier = Modifier
                .fillMaxWidth()
                .height(40.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Refresh,
                contentDescription = "复位"
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "复位缩放和位置",
                fontSize = 14.sp
            )
        }
    }
}

/**
 * 添加预览窗口组件
 */
@Composable
fun PreviewWindow(
    bitmap: Bitmap?,
    spec: PhotoSpec?,
    dpi: Float,
    onDismiss: () -> Unit
) {
    if (bitmap == null || spec == null) return
    
    Surface(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        color = Color.Black.copy(alpha = 0.7f)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = "预览: ${spec.name} (${spec.width}×${spec.height}mm, ${dpi}DPI)",
                color = Color.White,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            Image(
                bitmap = bitmap.asImageBitmap(),
                contentDescription = "预览图",
                modifier = Modifier
                    .weight(1f)
                    .clip(RoundedCornerShape(8.dp)),
                contentScale = ContentScale.Fit
            )
            
            Button(
                onClick = onDismiss,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF14B8A6)
                ),
                modifier = Modifier
                    .padding(top = 16.dp)
                    .fillMaxWidth()
            ) {
                Text("关闭预览")
            }
        }
    }
} 